<template>
  <div class="min-h-screen animate-fade-in">
    <!-- 导航栏 -->
    <nav class="glass shadow-sm">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between h-16">
          <div class="flex items-center">
            <button 
              @click="$router.back()" 
              class="mr-4 text-gray-600 hover:text-gray-900 transition-colors"
            >
              <i class="fas fa-arrow-left"></i>
            </button>
            <h1 class="text-xl font-bold text-gray-900">
              <i class="fas fa-plus mr-2"></i>
              创建预约
            </h1>
          </div>
          <div class="flex items-center">
            <span class="text-gray-600">
              <i class="fas fa-user mr-1"></i>
              {{ authStore.user?.nickname }}
            </span>
          </div>
        </div>
      </div>
    </nav>

    <!-- 主要内容 -->
    <main class="max-w-2xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
      <div class="glass rounded-lg shadow-xl p-8 animate-slide-up">
        <form @submit.prevent="handleSubmit" class="space-y-6">
          <!-- 基本信息 -->
          <div class="space-y-4">
            <h3 class="text-lg font-semibold text-gray-900">基本信息</h3>
            
            <div>
              <label class="block text-sm font-medium text-gray-700">预约标题 *</label>
              <input 
                type="text" 
                v-model="form.title" 
                required 
                class="input-field"
                placeholder="给你的预约起个标题..."
              >
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700">游戏名称 *</label>
              <input 
                type="text" 
                v-model="form.game" 
                required 
                class="input-field"
                placeholder="例如：王者荣耀、CS2、原神..."
              >
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700">游戏类型 *</label>
              <select v-model="form.category" required class="input-field">
                <option value="">请选择游戏类型</option>
                <option value="1">MOBA</option>
                <option value="2">FPS</option>
                <option value="3">RPG</option>
                <option value="4">RTS</option>
                <option value="5">MMO</option>
                <option value="6">其他</option>
              </select>
            </div>
          </div>

          <!-- 详细信息 -->
          <div class="space-y-4">
            <h3 class="text-lg font-semibold text-gray-900">详细信息</h3>
            
            <div>
              <label class="block text-sm font-medium text-gray-700">预约描述 *</label>
              <textarea 
                v-model="form.description" 
                required 
                class="input-field" 
                rows="4"
                placeholder="描述一下你的需求，比如需要什么位置、段位要求等..."
              ></textarea>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700">最大人数 *</label>
                <select v-model="form.maxPlayers" required class="input-field">
                  <option value="">选择人数</option>
                  <option value="2">2人</option>
                  <option value="3">3人</option>
                  <option value="4">4人</option>
                  <option value="5">5人</option>
                  <option value="6">6人</option>
                  <option value="10">10人</option>
                </select>
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700">预约时间 *</label>
                <input 
                  type="datetime-local" 
                  v-model="form.scheduledTime" 
                  required 
                  class="input-field"
                  :min="minDateTime"
                >
              </div>
            </div>
          </div>

          <!-- 错误信息 -->
          <div v-if="error" class="text-red-600 text-sm bg-red-50 p-3 rounded-md">
            {{ error }}
          </div>

          <!-- 提交按钮 -->
          <div class="flex justify-end space-x-4">
            <button 
              type="button" 
              @click="$router.back()"
              class="px-6 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 transition-colors"
            >
              取消
            </button>
            <button 
              type="submit" 
              :disabled="loading"
              class="btn-primary disabled:opacity-50 px-6 py-2"
            >
              {{ loading ? '创建中...' : '创建预约' }}
            </button>
          </div>
        </form>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useAppointmentsStore } from '@/stores/appointments'

const router = useRouter()
const authStore = useAuthStore()
const appointmentsStore = useAppointmentsStore()

const form = ref({
  title: '',
  game: '',
  category: '',
  description: '',
  maxPlayers: '',
  scheduledTime: ''
})

const error = ref('')
const loading = ref(false)

// 计算最小时间（当前时间）
const minDateTime = computed(() => {
  const now = new Date()
  now.setMinutes(now.getMinutes() - now.getTimezoneOffset())
  return now.toISOString().slice(0, 16)
})

const handleSubmit = async () => {
  error.value = ''
  loading.value = true

  try {
    // 验证表单
    if (!form.value.title.trim()) {
      error.value = '请输入预约标题'
      return
    }

    if (!form.value.game.trim()) {
      error.value = '请输入游戏名称'
      return
    }

    if (!form.value.description.trim()) {
      error.value = '请输入预约描述'
      return
    }

    if (form.value.maxPlayers < 2) {
      error.value = '最大人数不能少于2人'
      return
    }

    // 创建预约
    const appointmentData = {
      title: form.value.title.trim(),
      game_name: form.value.game.trim(),
      category_id: form.value.category ? parseInt(form.value.category) : null,
      description: form.value.description.trim(),
      max_players: parseInt(form.value.maxPlayers),
      scheduled_time: form.value.scheduledTime
    }

    const result = await appointmentsStore.createAppointment(appointmentData)

    if (result.success) {
      router.push('/home')
    } else {
      error.value = result.message
    }
  } catch (err) {
    error.value = '创建失败，请重试'
  } finally {
    loading.value = false
  }
}

const formatDateTime = (dateTimeString) => {
  const date = new Date(dateTimeString)
  return date.toLocaleString('zh-CN', {
    month: 'numeric',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

onMounted(() => {
  // 设置默认时间为1小时后
  const defaultTime = new Date()
  defaultTime.setHours(defaultTime.getHours() + 1)
  defaultTime.setMinutes(0)
  defaultTime.setMinutes(defaultTime.getMinutes() - defaultTime.getTimezoneOffset())
  form.value.scheduledTime = defaultTime.toISOString().slice(0, 16)
})
</script>
